package com.example.mysample.diy.pool;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.sql.*;

/**
 * @author YangXu
 * @date 2022/3/4
 * @description:
 */
@Slf4j
public class PoolTest {

    @Test
    public void test() {
        insertDemoData();
    }

    private Connection createConnection() {
        Connection conn;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://150.158.41.14:3306/test_db?useUnicode=true&characterEncoding=UTF-8",
                    "baibaox", "baibaox2021_yx@");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return conn;
    }

    private void executeQuery(Connection connection) {
        try {
            PreparedStatement ps = connection.prepareStatement("select * from user where id = 1");
            ResultSet resultSet = ps.executeQuery();
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                log.info("connection:[{}]查询返回 => id: {}, name: {}, age: {}", connection, id, name, age);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void insertDemoData() {
        for (int i = 0; i < 100; i++) {
            StringBuffer sb = new StringBuffer();
            sb.append("INSERT INTO test_db.base_staff\n" +
                    "(id, corp_id, account_id, name, mobile, email, gender, avatar, status, create_time, sort_num) VALUES ");
            boolean first = true;
            long corpId = IdUtil.getSnowflakeNextId();
            int randomInt = RandomUtil.randomInt(10000, 20000);
            for (int j = 0; j < randomInt; j++) {
                long accountId = IdUtil.getSnowflakeNextId();
                long staffId = IdUtil.getSnowflakeNextId();
                Long mobile = RandomUtil.randomLong(13100000000L, 18999999999L);

                String sqlValues = "('" + staffId + "', '" + corpId + "', '" + accountId + "', '员工" + j + "', '" + mobile + "', '" + mobile + "@qq.com', 0, '', 1, CURRENT_TIMESTAMP, " + j + ")";
                if (first) {
                    first = false;
                } else {
                    sb.append(",");
                }
                sb.append(sqlValues);
            }
            try {
                Connection connection = createConnection();
                PreparedStatement preparedStatement = connection.prepareStatement(sb.toString());
                preparedStatement.execute();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            } finally {
            }
        }
    }
}
